package admin

import (
	"github.com/gin-gonic/gin"
	"goadmin/models"
	"strconv"
)

type RoleController struct {
	BaseController
}

// 角色分页列表
func (con RoleController) Index(c *gin.Context) {
	roleList := []models.Role{}
	res := models.DB.Preload("Permissions").Find(&roleList)
	if res.Error != nil {
		con.errorMessage(c, "查询异常", 201)
		return
	}
	con.pageSuccess(c, roleList, res.RowsAffected)
}
func (con RoleController) UpdateRole(c *gin.Context) {
	idStr := c.Param("id")         // ① 取字符串
	id, err := strconv.Atoi(idStr) // ② 转 int
	if err != nil {
		con.errorMessage(c, "Id有误", 201)
		return
	}
	var req struct {
		Description string `binding:"required" json:"description"`
		Permissions []int  `json:"permissions" binding:"required"`
		RoleName    string `binding:"required" json:"role_name"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		con.errorMessage(c, err.Error(), 201)
		return
	}
	updateData := map[string]interface{}{
		"Description": req.Description,
		"RoleName":    req.RoleName,
	}
	result := models.DB.Model(&models.Role{}).Where("id = ?", id).Updates(updateData)
	result2 := models.DB.Where("role_id = ?", id).Delete(&models.RolePermissions{})
	rolePermissionsData := make([]*models.RolePermissions, 0, len(req.Permissions))
	for _, v := range req.Permissions {
		rolePermissionsData = append(rolePermissionsData, &models.RolePermissions{
			RoleID: id,
			MenuID: int(v),
		})
	}
	result3 := models.DB.Create(rolePermissionsData)
	if result.Error != nil && result2.Error != nil && result3.Error != nil {
		con.errorMessage(c, "程序错误", 201)
		return
	}
	if result.RowsAffected == 0 {
		con.errorMessage(c, "数据未更新", 201)
		return
	}
	con.successMessage(c, "更新成功", nil)
}

func (con RoleController) DeleteRole(c *gin.Context) {
	idStr := c.Param("id")         // ① 取字符串
	id, err := strconv.Atoi(idStr) // ② 转 int
	if err != nil {
		con.errorMessage(c, "Id有误", 201)
		return
	}
	result := models.DB.Delete(&models.Role{}, id)
	if result.Error != nil {
		con.errorMessage(c, "查询异常", 201)
		return
	}
	con.successMessage(c, "删除成功", nil)
}
